/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package qgj;

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

/**
 *
 * Must be a JDialog to hide from task bar.
 * @author ginger
 */
public class MainFrame extends javax.swing.JDialog {

    private int offsetX, offsetY;
    
    private JLabel[] jLblStocks;
    private JButton jBtnPrev, jBtnNext;
    
    public CfgFrame cfg_frame;
    private MainFrame main_frame;
    public ArrayList mStocks;
    
    /**
     * Query Value thru Data Interface.
     * 
     */
    private HashMap mQueryValue;
    private Image image;
    
    /**
     * Creates new form MainFrame
     */
    public MainFrame(Image image) {
        this.image = image;
        initComponents();
        this.setLocation(333,222);
        this.setSize(222,222);
        this.dispose();
        this.setUndecorated(true);  // no title
        //this.setVisible(true);
        this.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        
        main_frame = this;
         
        // Trays
        SystemTray tray = SystemTray.getSystemTray();
        //Image image  = Toolkit.getDefaultToolkit().getImage("D:\\user\\Documents\\NetBeansProjects\\OpkWin\\src\\opkwin\\1.jpg");
        //Image image_tmp  = Toolkit.getDefaultToolkit().getImage("logo.jpg");
        //image = image_tmp.getScaledInstance(24, 24, Image.SCALE_DEFAULT);
        PopupMenu popupMenu = new PopupMenu();
        MenuItem  miExit  = new MenuItem("Exit");
        MenuItem  miConfig  = new MenuItem("Config ..");
        MenuItem  miAbout = new MenuItem("About ..");
        MenuItem  miSep_0 = new MenuItem("-"); 
//        MenuItem  menuItemc  = new MenuItem("menu c");
//        MenuItem  menuItemd = new MenuItem("menu d");
        popupMenu.add(miConfig);
        popupMenu.add(miAbout);
//        popupMenu.add(menuItemc);
//        popupMenu.add(menuItemd);
        popupMenu.add(miSep_0);
        popupMenu.add(miExit);
        Image image_icon = image.getScaledInstance(24, 24, Image.SCALE_DEFAULT);
        TrayIcon trayIcon = new TrayIcon(image_icon, "que gu jiu v1.0",  popupMenu);
        // Tray Icon Message Handling
        trayIcon.addMouseListener(new java.awt.event.MouseAdapter() {
    @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                //JOptionPane.showMessageDialog(null, "Clicked!", "title..", JOptionPane.INFORMATION_MESSAGE);
                main_frame.setVisible(!main_frame.isVisible());                
            }
        });
        miExit.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null, "Clicked Exit!", "title..", JOptionPane.INFORMATION_MESSAGE);
                System.exit(0);
            }
        });
        miConfig.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null, "Clicked Exit!", "title..", JOptionPane.INFORMATION_MESSAGE);
                cfg_frame.setVisible(true);
            }
        });
        miAbout.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ImageIcon icon = new ImageIcon();
                icon.setImage(main_frame.image.getScaledInstance(48, 48, Image.SCALE_DEFAULT));
                JOptionPane.showMessageDialog(null, "Que Gu Jiu v1.0\ngingerluo@gmail.com", "About..", JOptionPane.INFORMATION_MESSAGE, icon);
            }
        });
        // Adding TrayIcon
        try {
            tray.add(trayIcon);
        } catch (AWTException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Below is ESC exit handling
        // TODO: remove this to minimize the window.
        Toolkit.getDefaultToolkit().addAWTEventListener(
                new AWTEventListener()
                {
                    @Override
                    public void eventDispatched(AWTEvent e) {
                        if (e.getID() == KeyEvent.KEY_PRESSED) {
                            KeyEvent evt = (KeyEvent) e;
                            if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
                                //System.exit(0);
                                main_frame.setVisible(false);
                            }
                        }
                    }
                }, AWTEvent.KEY_EVENT_MASK);
        
        // Create and Config CfgFrame
        cfg_frame = new CfgFrame(image);
        mStocks = cfg_frame.mCfg.mStocks;
        // UI settings
        this.setLayout(new FlowLayout(FlowLayout.LEFT,10,0));
        jLblStocks = new JLabel[5];
        for (int i = 0; i < 5; i++) {
            jLblStocks[i] = new JLabel("");
            //jLblStocks[i].setBackground(Color.GREEN);
            this.getContentPane().add(jLblStocks[i]);
        }
        jBtnPrev = new JButton("<<");
        jBtnNext = new JButton(">>");
        jBtnPrev.setSize(30, 20);
        jBtnNext.setSize(30, 20);
        this.getContentPane().add(jBtnPrev);
        this.getContentPane().add(jBtnNext);
        this.setOpacity(0.5f);
        this.setAlwaysOnTop(true);
        // Set mouse motion listner to Button
        //MouseMotionListener[] mm = this.getMouseMotionListeners();
//        for (int i=0; i < mm.length; i++) {
//            mm[i].
//            jBtnPrev.addMouseMotionListener(mm[i]);
//            jBtnNext.addMouseMotionListener(mm[i]);
//        }
        MouseMotionAdapter mm = new java.awt.event.MouseMotionAdapter() {
            @Override
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        };
        MouseAdapter ma = new java.awt.event.MouseAdapter() {
            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                formMouseExited(evt);
            }
        };
        jBtnPrev.addMouseMotionListener(mm);
        jBtnNext.addMouseMotionListener(mm);
        jBtnPrev.addMouseListener(ma);
        jBtnNext.addMouseListener(ma);
        
        _refresh();
        _timer();   // set timer
    }

    
    /**
     * Refresh from the config data.
     */
    private void _refresh() {
        try {
            mQueryValue = DataIntf.process(mStocks);
        } catch (NullPointerException e) { System.out.println("Refresh failed.");}
        // TODO: make it can select by line
        //int stock_num = mStocks.size();
        //final int NUM_PER_LINE  = 5; // 5 per line
        //int lines = stock_num / NUM_PER_LINE;

        //Iterator iter = mQueryValue.keySet().iterator();
        //stock_num = mQueryValue.size();
        //this.setSize(stock_num * 180 + 100, 30);
        //this.getGraphics().getFontMetrics();
        Object[] keys = mQueryValue.keySet().toArray();
        int window_width = 0;
        for (int i = 0; i < 5; i++) {
            if (i >= keys.length) {
                jLblStocks[i].setText("");
                window_width += jLblStocks[i].getWidth();
                break;
            } // FIXME: handle prev/next button
            String code = (String) keys[i];
            StockStruct ss = (StockStruct) mQueryValue.get(code);
            float amplify;
            if (ss.pc!=0)
                 amplify = 100 * (ss.la - ss.pc) / ss.pc;
            else
                amplify = 99;
            String item = String.format(" <%s:  %3.2f  %3.2f%%>  ", ss.na, ss.la, amplify);
            jLblStocks[i].setText(item);
            if (amplify >= 0)
                jLblStocks[i].setForeground(Color.red);
            else
                jLblStocks[i].setForeground(Color.blue);
            window_width += jLblStocks[i].getWidth();
        }
        this.setSize(window_width + jBtnPrev.getWidth() * 2 + 70, 30);
    }
    
    /**
     * Set Timer to run the refresh routine.
     * Every 5000 m-secs a refresh.
     */
    private void _timer() {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(
            new TimerTask() {
                @Override
                public void run() {
                    //throw new UnsupportedOperationException("Not supported yet.");
                    _refresh();
                    System.out.println("timer again");
                }
            }, 1000, 5000); // end timer schedule
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseExited(java.awt.event.MouseEvent evt) {
                formMouseExited(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                formMousePressed(evt);
            }
        });
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                formMouseDragged(evt);
            }
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 627, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 25, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed
        offsetX = evt.getX();
        offsetY = evt.getY();
    }//GEN-LAST:event_formMousePressed

    private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged
        java.awt.Component c = (Component) evt.getSource();
        c.setLocation(evt.getXOnScreen() - offsetX, evt.getYOnScreen()- offsetY);
    }//GEN-LAST:event_formMouseDragged

    // Handle mouse hover: less Opaque.
    private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
        this.setOpacity(0.9f);
    }//GEN-LAST:event_formMouseMoved

    private void formMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseExited
        this.setOpacity(0.5f);
    }//GEN-LAST:event_formMouseExited

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MainFrame(null).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}